package com.runshu.newsmartark.base;

import android.app.ActivityManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;


import com.alibaba.fastjson.JSON;
import com.example.controllibrary.LockControl;
import com.runshu.newsmartark.activity.TakeStockDtaActivity;
import com.runshu.newsmartark.common.ConstantUrl;
import com.runshu.newsmartark.dbutil.DBUtils;
import com.runshu.newsmartark.entity.MqttBean;
import com.runshu.newsmartark.entity.UserInfoEntity;
import com.runshu.newsmartark.event.BindEventBus;
import com.runshu.newsmartark.event.Event;
import com.runshu.newsmartark.event.EventBusUtils;
import com.runshu.newsmartark.event.EventCode;
import com.runshu.newsmartark.mvp.contract.ReadCardContract;
import com.runshu.newsmartark.mvp.model.ReadCardModel;
import com.runshu.newsmartark.mvp.presenter.ReadCardPresenter;
import com.runshu.newsmartark.network.netbean.ResponseBean;
import com.runshu.newsmartark.networkstate.NetworkBus;
import com.runshu.newsmartark.smartbox.SmartBoxHelper;
import com.runshu.newsmartark.util.FinishActivityManager;
import com.runshu.newsmartark.util.ListUtils;
import com.runshu.newsmartark.util.MQTTManager;
import com.runshu.newsmartark.util.MacUtils;
import com.runshu.newsmartark.util.SerialPortFinder;
import com.runshu.newsmartark.util.ToolScanner;
import com.runshu.newsmartark.util.UserCardUtil;
import com.runshu.newsmartark.util.common.LogUtil;
import com.runshu.newsmartark.util.common.SharedPreferencesUtils;
import com.runshu.newsmartark.util.common.ToastUtils;
import com.runshu.newsmartark.util.y.nativelog.NLogUtil;
import com.umeng.analytics.MobclickAgent;

import java.util.Objects;

import butterknife.ButterKnife;
import butterknife.Unbinder;
import cn.com.example.rfid.driver.Driver;
import cn.com.example.rfid.driver.RfidDriver;

import static com.runshu.newsmartark.common.ConstantUrl.REMOTE_CHECK_RFID;
import static com.runshu.newsmartark.common.ConstantUrl.REMOTE_OPEN;
import static com.runshu.newsmartark.common.ConstantUrl.Share_PartPort;
import static com.runshu.newsmartark.common.ConstantUrl.Share_hasAuth;
import static com.runshu.newsmartark.common.ConstantUrl.Share_isAdmin;
import static com.runshu.newsmartark.util.MQTTManager.PUB_TOPIC;


public abstract class BaseActivity extends AppCompatActivity implements ToolScanner.OnScanSuccessListener, ReadCardContract.View {
    public Context context;
    private Unbinder mButterBind;
    protected RelativeLayout container;
    public Bundle saveInstanceState;
    private ToolScanner toolScanner;
    protected final String TAG = this.getClass().getName();
    Driver driver;
    private SerialPortFinder mSerialPortFinder;
    String[] entries = null;
    //    private CallBackPanDianListener callBackPanDianListener;
    private ReadCardPresenter readCardPresenter;
    private boolean closeCurrent;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.saveInstanceState = savedInstanceState;
        context = this;
        toolScanner = new ToolScanner(this);
        FinishActivityManager.getManager().addActivity(this);
        container = new RelativeLayout(context);
        container.addView(LayoutInflater.from(context).inflate(getLayoutId(), null, false), new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
        setContentView(container, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
        mButterBind = ButterKnife.bind(this);
        // 若使用BindEventBus注解，则绑定EventBus
        if (this.getClass().isAnnotationPresent(BindEventBus.class)) {
            EventBusUtils.register(this);
        }
        mSerialPortFinder = new SerialPortFinder();
        entries = mSerialPortFinder.getAllDevices();
        if (ListUtils.hasTtyS1(entries, "ttyS1 (serial)")) {
            SharedPreferencesUtils.put(MyApplication.getApplication(), ConstantUrl.Share_PartPort, "dev/ttyS1");
        } else {
            SharedPreferencesUtils.put(MyApplication.getApplication(), ConstantUrl.Share_PartPort, "dev/ttyACM2");

        }
        driver = new RfidDriver();
        int Status;
        Status = driver.initRFID((String) SharedPreferencesUtils.get(MyApplication.getApplication(), Share_PartPort, "dev/ttyACM2"), 115200);
        if (-1000 == Status) {
            return;
        }
        Log.i("Connect", "Com:/dev/ttyACM2");

        initView();
        initData();
        bindListener();
        NLogUtil.i(NLogUtil.INFO_RestartAPP_APPINFO, "version:" + MacUtils.getLocalVersion(this));
//        getWindow().addFlags( WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        initMqtt();
        readCardPresenter = new ReadCardPresenter(this, new ReadCardModel());


    }
//
//    public void setListener(CallBackPanDianListener listener) {
//        this.callBackPanDianListener = listener;
//    }

    /**
     * 设置布局id
     *
     * @return
     */
    protected abstract int getLayoutId();

    /**
     * 初始控件 做一些findviewbyId
     */
    protected abstract void initView();

    @Override
    public void onScanSuccess(String barcode) {

    }

    @Override
    public void verifyIcCardSuccess(ResponseBean responseBean) {
        UserInfoEntity userEntity = (UserInfoEntity) responseBean.pullData();
        if (userEntity != null) {
            MyApplication.application.setUserInfoEntity(userEntity);
            loginSuccess();
            goTakeStock(BaseActivity.this);
            if (closeCurrent) BaseActivity.this.finish();
        }
    }

    @Override
    public void onError(String msg) {
        ToastUtils.showText(msg);

    }

    public void scanToOpenDoor(String barcode, boolean closeCurrent) {
        if (barcode == null || TextUtils.isEmpty(barcode))
            return;
        this.closeCurrent = closeCurrent;
        String s1;
        if (UserCardUtil.isHexStrValid(barcode)) {
            s1 = UserCardUtil.reverseCardId(barcode);
        } else {
            String s = UserCardUtil.decimal2Hex(barcode);
            s1 = UserCardUtil.reverseCardId(s);
        }
        LogUtil.e("卡号：", barcode + " 转换后===" + s1);
//        readCardPresenter.verifyIcCard(s1);
        new Thread(new Runnable() {
            @Override
            public void run() {

                UserInfoEntity userEntity = DBUtils.getInstance().getUserByIdCardNo(s1);
                if (userEntity != null) {
                    //成功
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            MyApplication.application.setUserInfoEntity(userEntity);
                            loginSuccess();
//                            if (isAdmin()) {
////                                if (userEntity.isAdmin()) {
////                                    Intent intent = new Intent(context, ManagerActivity.class);
////                                    startActivity(intent);
////                                    finish();
////                                } else {
////                                    Intent intent = new Intent(context, MainActivity.class);
////                                    startActivity(intent);
////                                    //发通知
////                                    EventBusUtils.sendEvent(new Event(EventCode.EventNOTADMIN));
////                                }
//                            } else
                                goTakeStock(BaseActivity.this);
                            if (closeCurrent) BaseActivity.this.finish();
                        }
                    });
                } else {
                    NLogUtil.i(NLogUtil.INFO_Scan_Card, "刷卡失败，未配置卡片 barCode:" + barcode);
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            ToastUtils.showText("没有配置卡片" + s1);
                        }
                    });
                }
            }
        }).start();
    }


    public void goTakeStock(Context context) {
        SmartBoxHelper.getInstance().openLightAndDoor(this, 0);
        Intent intents = new Intent(context, TakeStockDtaActivity.class);
        startActivity(intents);
    }


    /**
     * 设置数据的显示
     */
    protected abstract void initData();

    /**
     * 设置点击事件
     */
    protected abstract void bindListener();

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        LogUtil.e("input=======", event.getDevice().getName());
        if ("Virtual".equals(event.getDevice().getName())) {
            return super.dispatchKeyEvent(event);
        }
        if (event.getKeyCode() != KeyEvent.KEYCODE_BACK) {
            toolScanner.analysisKeyEvent(event);
            return true;
        }
        return super.dispatchKeyEvent(event);


    }

    /**
     * 权限检查
     *
     * @param neededPermissions 需要的权限
     * @return 是否全部被允许
     */
    protected boolean checkPermissions(String[] neededPermissions) {
        if (neededPermissions == null || neededPermissions.length == 0) {
            return true;
        }
        boolean allGranted = true;
        for (String neededPermission : neededPermissions) {
            allGranted &= ContextCompat.checkSelfPermission(this, neededPermission) == PackageManager.PERMISSION_GRANTED;
        }
        return allGranted;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        boolean isAllGranted = true;
        for (int grantResult : grantResults) {
            isAllGranted &= (grantResult == PackageManager.PERMISSION_GRANTED);
        }
        afterRequestPermission(requestCode, isAllGranted);
    }

    /**
     * 请求权限的回调
     *
     * @param requestCode  请求码
     * @param isAllGranted 是否全部被同意
     */
    protected abstract void afterRequestPermission(int requestCode, boolean isAllGranted);

    protected void showToast(String s) {
        Toast.makeText(getApplicationContext(), s, Toast.LENGTH_SHORT).show();
    }

    protected void showLongToast(String s) {
        Toast.makeText(getApplicationContext(), s, Toast.LENGTH_LONG).show();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        FinishActivityManager.getManager().finishActivity(this);
        mButterBind.unbind();
        // 若使用BindEventBus注解，则解绑定EventBus
        if (this.getClass().isAnnotationPresent(BindEventBus.class)) {
            EventBusUtils.unregister(this);
        }
//        HttpExecutor.cancleAllRequest();
    }

    /**
     * 是否身份认证过了
     *
     * @return
     */
    public boolean hasAuth() {

        return (boolean) SharedPreferencesUtils.get(context, Share_hasAuth, false);

    }

    public void exitLogin() {
        SmartBoxHelper.getInstance().reset();
        SharedPreferencesUtils.put(context, Share_hasAuth, false);
        MyApplication.application.removeUserInfo();
    }

    public void loginSuccess() {
        SharedPreferencesUtils.put(context, Share_hasAuth, true);
    }

    /**
     * 是否是管理
     *
     * @return
     */
    public void setisAdmin() {
        SharedPreferencesUtils.put(context, Share_isAdmin, true);
    }

    public boolean isAdmin() {
        return (boolean) SharedPreferencesUtils.get(context, Share_isAdmin, false);
    }

    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
        NetworkBus.getDefault().register(BaseActivity.this);

    }

    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onResume(this);
        NetworkBus.getDefault().unregister(BaseActivity.this);

    }

    private boolean isTopActivity(String activityClassName) {
        boolean isTop = false;
        ActivityManager am = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
        ComponentName cn = am.getRunningTasks(1).get(0).topActivity;
        if (cn.getClassName().contains(activityClassName)) {
            isTop = true;
        }
        return isTop;
    }

    public void initMqtt() {
        MQTTManager mqttManager = MQTTManager.getInstance(context);
        assert mqttManager != null;
        mqttManager.setMessageHandlerCallBack((topicName, s) -> runOnUiThread(() -> {
            Log.e(TAG, "messageSuccess: " + s + " topicName = " + topicName + TAG);
            try {
                MqttBean mqttBean = JSON.parseObject(s, MqttBean.class);
                MqttBean.BodyBean mqttBeanBody = new MqttBean.BodyBean();

                if ("activity.MainActivity".equals(FinishActivityManager.getManager().currentActivity().getLocalClassName())) {
                    if (mqttBean.getHeader().getCommand().equals(REMOTE_OPEN)) {
                        //开门
                        mqttBeanBody.setCommCode(1);
                        mqttBeanBody.setOpenStatus(1);
                        mqttBeanBody.setLockStatus(1);
                        mqttBean.setBody(mqttBeanBody);
                        //发送信息
                        mqttManager.publish(PUB_TOPIC, JSON.toJSONString(mqttBean), false, 0);
                        UserInfoEntity userInfoEntity = new UserInfoEntity();
                        userInfoEntity.setUserCode(mqttBean.getHeader().getUserCode());
                        userInfoEntity.setUserName(mqttBean.getHeader().getUserName());
                        MyApplication.application.setUserInfoEntity(userInfoEntity);
                        loginSuccess();
                        goTakeStock(context);
                    } else if (mqttBean.getHeader().getCommand().equals(REMOTE_CHECK_RFID)) {
                        //盘点
                        EventBusUtils.sendEvent(new Event(EventCode.EventPanDian, mqttBean));
                    }
                } else {


                    mqttManager.publish(PUB_TOPIC, JSON.toJSONString(mqttBean), false, 0);

                }
            } catch (Exception e) {
                Log.d(TAG, Objects.requireNonNull(e.getMessage()));
            }


        }));
    }
    /**
     * 跳转到指定的页面
     *
     * @param clazz
     */
    public void startActivity(Class clazz) {
        Intent intent = new Intent(this, clazz);
        startActivity(intent);
    }

}
